package com.wbxqy.car_management_system.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {

    private static final String UPLOAD_DIR = "D:/img"; // 替换为你的上传目录
    private static final String FILE_URL_PREFIX = "http://localhost:9999/img/"; // 替换为你的文件访问URL前缀

    @PostMapping
    public ResponseEntity<?> handleFileUpload(@RequestParam("file") MultipartFile file) {
        try {
            String filename = file.getOriginalFilename();
            String uniqueFilename = UUID.randomUUID().toString() + "_" + filename;
            Path path = Paths.get(UPLOAD_DIR, uniqueFilename);
            Files.write(path, file.getBytes());
            String fileUrl = FILE_URL_PREFIX + uniqueFilename;
            return ResponseEntity.ok().body(Map.of("url", fileUrl));
        } catch (Exception e) {
            return ResponseEntity.status(500).body("File upload failed: " + e.getMessage());
        }
    }
}
